$(function() {
	//绑定机构下拉列表
	bindOrg2('org');
	
	$('#submit').click(function(){
		save(true, $(this));
	})	
	$('#save').click(function(){
		save(false, $(this));
	})
	
	initFileInput('upload', {'busscode': '02'}, null);
//	上传文本控件关闭事件 -- 清除内容
	$('#fileuploadmodal').on('hide.bs.modal', function () {
        setTimeout(function(){
        	$('.fileinput-remove').trigger('click');
        }, 1000);
	})
	
	$('#fileuploadmodal').modal({
		keyboard: false,
		backdrop:"static",
		show: false
	})
})

//获取坐标数据
function getCoordinateData(){
	var coordinateDatas = [];

	$('.coordinateForm').each(function(){
		var coordinateData = $(this).serializeObject1();
		coordinateDatas.push(coordinateData);
	});
	
	return coordinateDatas;
}

//获取设备及主要技术参数数据
function getDeviceData(){
	var deviceDatas = [];
	
	$('.deviceForm').each(function(index,el){
		var deviceData = $(this).serializeObject1();
		if(!jQuery.isEmptyObject(deviceData) && deviceData.devicename != '' && deviceData.summary != ''){
			deviceData.serialnumber = index + 1;
			deviceDatas.push(deviceData);
		}
	});
	
	return deviceDatas;
}

function save(issubmit, obj){
	
	var param = {};
	var applyData = $('#Apply').serializeObject();
	var businessData = $('#Business').serializeObject();
	
	var materialData = getMaterialData();
	var coordinateData = getCoordinateData();
	var deviceData = getDeviceData();
	
	param['issubmit'] = issubmit;
	param['Apply'] = applyData;
	param['Business'] = businessData;
	param['Material'] = materialData;
	param['Coordinate'] = coordinateData;
	param['Device'] = deviceData;
//	param['Verify'] = [];

	var shipData = [];
//	var verify = [];
//	var verifyflag = false;
//	var verifyresult = false ;
	if(undefined != $('#ship').attr('data')){
		var data = JSON.parse($('#ship').attr('data'));
//		if(data.verifyresult == 4){   //校验未完成
//			verifyflag = true;
//			return ;
//		}
//		if(data.verifyresult == -1){  //校验未通过
//			verifyresult = true;
//			return ;
//		}
//		if("verify" in data){
//		 for(var i = 0 ; i < data.verify.length ; i++)
//		  verify.push(data.verify[i]);
//		}
//		delete data["verify"];
		shipData.push(data);
	}
	$('[name="ship"]').each(function(){
		var data = $(this).val();
		data = JSON.parse(data);
		// 需要额外添加水上水下添加主要技术参数
//		if($('#'+data.shipidnumber).length > 0){
//			data.technicalparameter = $('#'+data.shipidnumber).val();
//		}
//		if(data.verifyresult == 4){
//			verifyflag = true;
//			return ;
//		}
//		if(data.verifyresult == -1){
//			verifyresult = true;
//			return ;
//		}
//		if("verify" in data){
//		 for(var i = 0 ; i < data.verify.length ; i++)
//		  verify.push(data.verify[i]);
//		}
//		delete data["verify"];
		shipData.push(data);
	});
//	if(verifyresult){
//		$.alert({
//		    title: '提示!',
//		    content: "船舶校验未通过，请重新选择船舶!",
//		    confirmButton: '确定'
//		});
//		return ;
//	}
//	if(verifyflag){
//		$.alert({
//		    title: '提示!',
//		    content: "船舶数据校验中，请在校验完成后操作!",
//		    confirmButton: '确定'
//		});
//		return ;
//	}
	if(shipData.length > 0){
		param['Ship']=shipData;
	}
	
//	if(verify.length > 0){
//		param['Verify'] = verify; 
//	}
	
	if(!checkData(param)){
		return;
	}
	
	if(getUrlParam('change') == '1')
		delete applyData['applyid'];

	obj.attr('disabled',true);
    $("body").mLoading("show");
    
	$.ajax({ 
		method: 'post',
		url: projectPath + 'business/apply.do',
		data: JSON.stringify(param),
        dataType: 'json',  
        contentType:'application/json;charset=UTF-8', 
		success: function(data){
			obj.attr('disabled',false);
            $("body").mLoading("hide");
			
			var msa = data.info;

			var applyno = "";
			if(data.result == 1){
				if(issubmit)
					msa = "提交成功！";
				else
					msa = "保存成功！";
				
				applyno = data.datas.applyno;
				msa += '<br/><span style="color:red;">申请单号是：' + applyno + '</span>'; 
			}
			
			if(data.result == 0 && msa.indexOf('申请备案') > 0){
				msa = msa + '<span style="color:red;">是否跳转到备案页面进行单位备案？</span>';
			}
			
			$.confirm({
			    title: '提示!',
			    content: msa,
			    confirmButton: '确定',
			    cancelButton: '取消',
			    confirm: function(){
			    	if(data.result == 1){
			    		var itemno = $('[name="itemno"]').val();
			    		window.location.href = "detail.html?applyno=" + applyno + "&itemno=" + itemno;
			    	}
			    	else if(data.result == 0 && msa.indexOf('申请备案') > 0){
			    		window.location.href = '/gahCSP/business/record.html';
			    	}
			    }
			});
		}
	});
}

var filecount = 0;
var filecountnow = 0;
function initFileInput(ctrlcss, params, data) {
	
	var urls = [];
	if(data != null){
		for(var i = 0; i < data.length; i++){
			urls[i] = data[i].url;
		}
	}
	
    var control = $('.' + ctrlcss);
    control.fileinput({
        theme: 'explorer-fa',
        language: 'zh', //设置语言
        uploadUrl: projectPath + "share/upload_fileinput.do", //上传的地址
		allowedFileExtensions : ['jpg', 'png','gif','txt','sql','xlsx','xls','pdf','pptx','docx','doc','jpeg'],//接收的文件后缀
        uploadExtraData: params,
        uploadAsync: true, //默认异步上传
        showUpload: true, //是否显示上传按钮
        showRemove : true, //显示移除按钮
        showPreview : true, //是否显示预览
        showCaption: false,//是否显示标题
        browseClass: "btn btn-primary", //按钮样式
        enctype: 'multipart/form-data',
        validateInitialCount:true,
        overwriteInitial: false,
        initialPreviewAsData: true,
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        initialPreview: urls,
	    initialPreviewConfig: data,

    }).on('filepreupload', function(event, data, previewId, index) {     //上传中
        var form = data.form, files = data.files, extra = data.extra,
        response = data.response, reader = data.reader;
        console.log('文件正在上传');
        filecount++;
    }).on("fileuploaded", function (event, data, previewId, index) {    //一个文件上传成功
        console.log('文件上传成功！');
        
        var resultData = data.response;
        var fileid = resultData.datas[0].fileid;
        var filename = '<p id="'+ fileid +'"><a href="/gahCSP/share/downFiles.do?filename='+ resultData.datas[0].filename +'&fileid='+ fileid +'">' + resultData.datas[0].filename + '</a><span class="glyphicon glyphicon-remove" style="color:red;cursor:pointer;" onclick="deleteFile(\''+ nowindex +'\', \''+ fileid +'\')"></span></p>';
        var fileids = $('#upload_' + nowindex).attr("fileid");
        var filenames = $('#filename_' + nowindex).html();
        if(fileids == ''){
        	fileids = fileid;
        	filenames = filename;
        }
        else{
        	fileids += ',' + fileid;
        	filenames += filename;
        }

        $('#upload_' + nowindex).attr("fileid", fileids);
        
        $('#filename_' + nowindex).html(filenames);

        $('#quantity_' + nowindex).val(fileids.split(',').length);
        
        filecountnow++;
        console.info(filecountnow);
        if(filecountnow == filecount)
        	$('#fileuploadmodal').modal('hide');
        
    }).on('fileerror', function(event, data, msg) {  //一个文件上传失败
        console.log('文件上传失败！'+data.id);
        filecountnow++;
    }).on('filepredelete', function(event, key, jqXHR, data) {  
        alert(key);   
        return;
    });  
}

function checkData(param){
	var check = true;
	var checkErrorStr = '';
	
//	param['Apply'] = applyData;
//	param['Business'] = businessData;
	
	var checkApplyStr = ['orgcode'];
	for(var i = 0; i < checkApplyStr.length; i++){
		if($('[name="'+checkApplyStr[i]+'"]').val() == ''){
			checkErrorStr += $('[name="'+checkApplyStr[i]+'"]').attr('placeholder') + '<br />';
		}
	}

	var itemno = $('[name="itemno"]').val();
	
	var checkBusinessStr = [];
	if(itemno == '1001')
		checkBusinessStr = ['shorelineuse','shorelinerange','business'];
	else if(itemno == '1002')
		checkBusinessStr = ['workname','worktypecode','workmethodcode','workposition','workbegintime','workendtime','days','buildunitname', 'workunitname', 'workarea'];	
	else if(itemno == '1004')
		checkBusinessStr = ['rescuename','rescuetime','rescuesite','rescuearea'];
	else if(itemno == '1005')
		checkBusinessStr = ['workname','workposition','workbegintime','workendtime','days','buildunitname', 'workunitname', 'workarea'];
//		checkBusinessStr = ['shipwrecksname','workbegintime','workendtime','days','workunitname','workarea'];
	else if(itemno == '1006')
		checkBusinessStr = ['towingname','workshipname','towingcontent'];
	else if(itemno == '1007' || itemno == '1008' || itemno == '1009' || itemno == '1010' || itemno == '1011')
		checkBusinessStr = ['business','definerange','defineterm','buildunitname'];
	else if(itemno == '2002')
		checkBusinessStr = ['workstarttime', 'workendtime', 'worktypename'];
	else if(itemno == '1013')
		checkBusinessStr = ['departureportcode','destinationportcode','freightsituation','eventtime','eventplace'];	
	else if(itemno == '1014')
		checkBusinessStr = ['oldapplyid','changetypecode','changecontent','workbegintime','workendtime','days'];
	else if(itemno == '1015')
		checkBusinessStr = ['business', 'workbegintime', 'workunitname', 'wordaddress'];
	else if(itemno == '2001')
		checkBusinessStr = ['watersname', 'entertime', 'leavetime', 'reason'];
	else if(itemno == '2003'){
		if($('[name="businesstype"]').val() == '02'){
			checkBusinessStr = ['businesstype', 'corporation', 'contactperson', 'contactidcard', 'contactphone', 'yachtclubname', 'berthwaters', 'agentperson', 'agentpidcard', 'agentphone', 'alteration', 'alterreason'];
		} else {
			checkBusinessStr = ['businesstype', 'corporation', 'contactperson', 'contactidcard', 'contactphone', 'yachtclubname', 'berthwaters', 'agentperson', 'agentpidcard', 'agentphone'];
		}
	} else if(itemno == '9001'){
		checkBusinessStr = ['engineeringname', 'investment', 'days', 'scale', 'projectsource', 'buildunitname', 'workunitname', 'maintainname'];
	} else if(itemno == '10002'){
		checkBusinessStr = ['shipname','flagcode','markcode','typecode','grosstonnage','enginepower'];
	} else if(itemno == '10003'){
		checkBusinessStr = ['username','sex','mobilephone','email'];
	}
	for(var i = 0; i < checkBusinessStr.length; i++){
		if($('[name="'+checkBusinessStr[i]+'"]').val() == ''){
			checkErrorStr += $('[name="'+checkBusinessStr[i]+'"]').attr('placeholder') + '<br />';
		}
	}
	
	if(itemno == '2001'){
		if($('[name="ship"]').length == 0) {
			checkErrorStr += '请选择船舶数据<br />';
		}
	}
	
	//判断申报附件是否必填
	$('#material').find('tbody').find('[must="true"]').each(function(){
		if('' == $(this).attr('fileid')){
			checkErrorStr += '请上传<span style="color:red;">' + $(this).attr('placeholder') + '</span><br />';
		}
	});

	if(checkErrorStr != ''){
		$.alert({
		    title: '提示!',
		    content: checkErrorStr,
		    confirmButton: '确定'
		});
		
		check = false;
	}
	
	return check;
}

function bindOrg1(obj){

	$.ajax({ 
		method: 'post',
		url: projectPath + "share/getOrg.do",
		dataType: "json",
		contentType: "application/json",
		success: function(data){
		    var cityPicker = new IIInsomniaCityPicker({
		        data: data,
		        target: '#' + obj,
		        callback: function(id){
		        	var id = $('#' + obj).attr("data");
		        	var name = $('#' + obj).val();
		        	
		        	$('#orgcode').val(id);
		        	$('#orgname').val(name);

		        	if($('#berthcode').length > 0)			//泊位
		            	bindBearth('berthcode', id , '');

		        	if($('#waterway').length > 0)			//水道
		        		bindWaterway('waterway', id , '');
		        }
		    });

		    cityPicker.init();
		}
	});
}

function bindOrg2(obj){
	$.ajax({ 
		method: 'post',
		url: projectPath + "share/getOrg.do",
		dataType: "json",
		contentType: "application/json",
		success: function(data){
			//常用海事机构
			var historyjson = data.hisResult;
			//海事机构
			var orgAlljson = data.result;
			
			var topCode = '000000';
			var orgList = JSON2ARRAY3(orgAlljson, topCode);
			var orgHistoryList = JSON2ARRAY2(historyjson);
			InitList(obj, topCode, orgList, orgHistoryList);
		}
	});
}

//获取许可项目的提交材料列表
function getMaterial(){
	$.ajax({ 
		url: projectPath + "business/getMaterial.do",
		dataType: "json",
		data: {"itemno": itemno},
		contentType: "application/json",
		success: function(data){
			if(data.result == 1){
				var materialList = data.datas;
				bindMaterial(materialList);
			}
		}
	});
}
var tableID = 'material';
function bindMaterial(materialList){
//	document.write(JSON.stringify(materialList));
	for(var i = 0; i < materialList.length; i++){
		var ismustsubmit = materialList[i]['ismustsubmit'];
		var ismustsubmitStr = "";
		var must = false;
		if(ismustsubmit == 1){
			ismustsubmitStr = '<span style="color:red;">*</span>';
			must = true;
		}
		var index = materialList[i]['serialnumber'];
		
		var trStr = '<tr>																								'+
					'	<td><span name="serialnumber">'+ index +'</span></td>													'+
					'	<td style="text-align: left;" id="materialname_'+ index +'"><span name="materialname">'+ materialList[i]['materialname'] + '</span>' + ismustsubmitStr +'</td>		'+
					'	<td><input name="quantity" id="quantity_'+index+'" type="number" class="form-control" value="0" /></td>									'+
					'	<td id="filename_'+ index +'">																							'+
					'	</td>																							'+
					'	<td><button type="button" id="upload_'+index+'" onclick="openModal('+index+')" class="btn btn-success" placeholder="'+ materialList[i]['materialname'] +'" must="'+ must +'" fileid=""><span class="glyphicon glyphicon-upload"></span>上传</button> 									'+
//					'		<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-minus"></span>删除</button> </td>								'+
					'</tr>';
		
		$('#' + tableID).find('tbody').append(trStr);
	}
}

function getMaterialData(){
	var materialDatas = [];
	$('#material').find('tbody').find('tr').each(function(){
		var serialnumber = $(this).find('[name="serialnumber"]').html();
		var materialname = $(this).find('[name="materialname"]').html();
		var quantity = $(this).find('[name="quantity"]').val();
		
		var materialData = {};
		materialData['serialnumber'] = serialnumber;
		materialData['materialname'] = materialname;
		materialData['quantity'] = quantity;
		
		if('' != $('#upload_' + serialnumber).attr('fileid')){
			var materialAnnexDatas = [];
			var fileids = $('#upload_' + serialnumber).attr('fileid');
			for(var i = 0; i < fileids.split(',').length; i++){
				var fileid = fileids.split(',')[i];		

				var materialAnnexData = {};
				materialAnnexData['fileid'] = fileid;
				
				materialAnnexDatas.push(materialAnnexData);
			}
			
			materialData['MaterialAnnex'] = materialAnnexDatas;
		}
		
		materialDatas.push(materialData);
	})
	
	return materialDatas;
}

var nowindex = 0;
function openModal(index){
	nowindex = index;
	
	$('#fileuploadmodal').modal('show');

	filecount = 0;
	filecountnow = 0;
}


function bindMaterialListForm(jsonMaterial){
//	document.write(JSON.stringify(jsonMaterial));
	for(var i = 0; i < jsonMaterial.length; i++){
		var index = jsonMaterial[i]['serialnumber'];
		var ismustsubmit = jsonMaterial[i]['ismustsubmit'];
		var iscorrection = jsonMaterial[i]['iscorrection'];
		var ismustsubmitStr = "";
		var must = false;
		if(iscorrection == 1){
			ismustsubmitStr = '<span style="color:red;">*</span>';
			must = true;
			
			$('#materialname_' + index).append(ismustsubmitStr);
			$('#upload_' + index).attr('must', must);
		}
		
		
		var quantity = jsonMaterial[i]['quantity'];
//		var materialname = jsonMaterial[i]['materialname'];
		var fileids=jsonMaterial[i]['fileid'];
		var fileurls = jsonMaterial[i]['fileurl'].split(',');

		for(var k=0; k<fileurls.length; k++){
			var fileurlStr = fileurls[k];
			
			if(fileurlStr != ""){
				var fileid = fileids.split(',')[k];
				fileurlStr = '<p id="'+ fileid +'">' + fileurlStr + '<span class="glyphicon glyphicon-remove" style="color:red;cursor:pointer;" onclick="deleteFile(\''+ index +'\', \''+ fileid +'\')"></span><br /></p>';
				$('#filename_' + index).append(fileurlStr);
			}
		}
		
//		$('#filename_' + index).html(fileurl);
		$('#upload_' + index).attr('fileid', fileids);
		$('#quantity_' + index).val(quantity);
		
//		$('#' + tableID).find('tbody').append(trStr);
	}
}


function deleteFile(index, fileid){
	var fileidsNew = "";
	var fileids = $('#upload_' + index).attr('fileid');
	for(var i=0; i<fileids.split(',').length; i++){
		if(fileids.split(',')[i] != fileid){
			fileidsNew += fileids.split(',')[i] + ',';
		}
	}
	if(fileids.split(',').length > 0)
		fileidsNew = fileidsNew.substring(0, fileidsNew.length - 1);
	
	$('#' + fileid).remove();

	$('#upload_' + index).attr('fileid', fileidsNew);
	$('#quantity_' + index).val($('#quantity_' + index).val()-1);
}

function checkInfo(data) {    //校验数据

	 $("tr[name = 'checkInfo']").remove();
	var certstr = "", img = "",fscstr = "";
	for(var i=0;i<data.length;i++){
		if(data[i].verifyresultcode == 0)
			img = '<img src="../img/jiaoyan2.png" alt="" style="width:20px;height:20px;">';
		else if(data[i].verifyresultcode == 1)
			img = '<img src="../img/jiaoyan1.png" alt="" style="width:20px;height:20px;">';
		else
			img = '<img src="../img/jiaoyan3.png" alt="" style="width:20px;height:20px;">';
		if(data[i].verifytypecode == "0101" || data[i].verifytypecode == "0102" || data[i].verifytypecode == "0104"){   //法定证书校验
			certstr += '<tr name="checkInfo">' + '	<td style="text-align: center">' + data[i].verifyname
			+ '</td>' + '	<td style="text-align: center">' + img + '</td>'
			+ '	<td style="text-align: center">' + data[i].verifyresultdesc + '</td>'
			+ '	<tr>';
		}else if(data[i].verifytypecode == "0105"){
			fscstr += '<tr name="checkInfo">' + '	<td style="text-align: center">' + data[i].verifyname
			+ '</td>' + '	<td style="text-align: center">' + img + '</td>'
			+ '	<td style="text-align: center">' + data[i].verifyresultdesc + '</td>'
			+ '	<tr>';
		}
	}
	$("#certShip").append(certstr); //法定证书校验
	$("#fsc").append(fscstr);
}

function getVerify(shipidnumber){   //获取校验数据
	console.log(shipidnumber);
	var param = {};
	param['shipidnumber']  = shipidnumber;
	param['applyid'] = applyid;
	console.log(param);
	$.ajax({ 
		method: 'post',
		url: basePath() + 'share/getverify.do',
		data: JSON.stringify(param),
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		checkInfo(data.datas.data)
	    	} 
	    	else{
	    		window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.error);
	    	}
      	}
	});
}
